<?php

/**
 * FileUploader Class
 *
 * @package    nfzz
 * @author     qq Guys
 * @modified   Francisco Calderón <fjcalderon@gmail.com>
 */

class UploadFileXhr {
    /**
     * Save the file to the specified path
     * @return boolean TRUE on success
     */
    public function save($path) {    
        $input = fopen("php://input", "r");
        $temp = tmpfile();
        $realSize = stream_copy_to_stream($input, $temp);
        fclose($input);
        
        if ($realSize != $this->getSize()){            
            return false;
        }
        
        $target = fopen($path, "w");        
        fseek($temp, 0, SEEK_SET);
        stream_copy_to_stream($temp, $target);
        fclose($target);
        
        return true;
    }
    public function getName() {
        return $_GET['qqfile'];
    }
    public function getSize() {
        if (isset($_SERVER["CONTENT_LENGTH"])){
            return (int)$_SERVER["CONTENT_LENGTH"];            
        } else {
            throw new Exception('Getting content length is not supported.');
        }      
    }   
}

class FileUploader {
    private $allowedExtensions = array();
    private $sizeLimit = 10485760;
    private $file;    
    private $imagetype = array( "jpg" => IMAGETYPE_JPEG, "gif" => IMAGETYPE_GIF, "png" => IMAGETYPE_PNG );
    public $filename;

    function __construct(array $allowedExtensions = array(), $sizeLimit = 10485760){        
        $allowedExtensions = array_map("strtolower", $allowedExtensions);
            
        $this->allowedExtensions = $allowedExtensions;        
        $this->sizeLimit = $sizeLimit;
        
        if (isset($_GET['qqfile'])) {
            $this->file = new UploadFileXhr();
        } else {
            $this->file = false; 
        }
    }
       
    /**
     * Returns array('success'=>true) or array('error'=>'error message')
     */
    function handleUpload($uploadDirectory, $replaceOldFile = FALSE){
        if (!is_writable($uploadDirectory)){
            return array('error' => "Server error. Upload directory isn't writable.");
        }
        
        if (!$this->file){
            return array('error' => 'No files were uploaded.');
        }
        
        $size = $this->file->getSize();
        
        if ($size == 0) {
            return array('error' => 'File is empty');
        }
        
        if ($size > $this->sizeLimit) {
            return array('error' => 'File is too large');
        }
        
        $pathinfo = pathinfo($this->file->getName());
        //$filename = $pathinfo['filename'];
        $filename = md5(uniqid());
        $ext = strtolower($pathinfo['extension']);
        $ext = ($ext == "jpeg")? "jpg" : $ext;

        if($this->allowedExtensions && !in_array($ext, $this->allowedExtensions)){
            $these = implode(', ', $this->allowedExtensions);
            return array('error' => 'File has an invalid extension, it should be one of '. $these . '.');
        }
               
        if(!$replaceOldFile){
            /// don't overwrite previous files that were uploaded
            while (file_exists($uploadDirectory . $filename . '.' . $ext)) {
                $filename .= rand(10, 99);
            }
        }
                       
        if ($this->file->save($uploadDirectory . $filename . '.' . $ext)){
            if (exif_imagetype($uploadDirectory . $filename . '.' . $ext) != $this->imagetype[$ext]) {
                unlink($uploadDirectory . $filename . '.' . $ext);
                return array('error'=> 'Could not save uploaded file.' .
                    'The file is not an valid '.$ext.' file');
            }
            $this->filename = $filename.".".$ext;
            return array('success'=>true, 'file' => $filename.".".$ext);
        } else {
            return array('error'=> 'Could not save uploaded file.' .
                'The upload was cancelled, or server error encountered');
        }
        
    }    
}
